package com.android.juguotang.activity;

import android.content.DialogInterface;
import android.os.Bundle;
import android.support.design.widget.FloatingActionButton;
import android.support.design.widget.Snackbar;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.Toolbar;
import android.view.View;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.android.juguotang.R;
import com.android.juguotang.adapt.CartAdapter;
import com.android.juguotang.app.BaseActivity;
import com.android.juguotang.model.ajaxcartCallback;
import com.android.juguotang.model.ajaxcartdata;
import com.android.juguotang.model.deletecartCallback;
import com.android.juguotang.model.deletecartdata;
import com.android.juguotang.model.getCartCallback;
import com.android.juguotang.model.getcartdata;
import com.android.juguotang.utils.ConstantsUrl;
import com.android.juguotang.utils.HttpUtils;
import com.android.juguotang.utils.MyLog;
import com.android.juguotang.utils.ObjectUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

import okhttp3.Call;

public class ProductCartUpdateActivity extends BaseActivity implements View.OnClickListener,CartAdapter.RefreshPriceInterface {

    private ProductCartUpdateActivity mcontext;
    private boolean networkConnected;
    private CartAdapter adapter;
    private ListView listView;
    private CheckBox cb_check_all;
    private TextView tv_delete;
    private double totalPrice = 0.00;
    private int totalCount = 0;
    private List<HashMap<String,String>> goodsList;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.content_product_cart_update);

        mcontext = ProductCartUpdateActivity.this;
        networkConnected = ObjectUtils.isNetworkConnected(mcontext);
        initDate();
        initView();
    }
    private void initView(){

        listView = (ListView) findViewById(R.id.listview);
        cb_check_all = (CheckBox) findViewById(R.id.all_chekbox);
        tv_delete = (TextView) findViewById(R.id.tv_delete);
        tv_delete.setOnClickListener(this);
        cb_check_all.setOnClickListener(this);


    }
    private void initDate(){
        getCart();;



    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.all_chekbox:
                AllTheSelected();
                break;

            case R.id.tv_delete:
                if(totalCount<=0){
                    Toast.makeText(mcontext,"请选择要删除的商品~",Toast.LENGTH_SHORT).show();
                    return;
                }
                checkDelete(adapter.getPitchOnMap());
                break;

        }
    }
    //删除操作
    private void checkDelete(final Map<String,Integer> map){
        final List<HashMap<String,String>> waitDeleteList=new ArrayList<>();
        final Map<String,Integer> waitDeleteMap =new HashMap<>();
        String ids="";
        for(int i=0;i<goodsList.size();i++){
            if(map.get(goodsList.get(i).get("id"))==1){
                waitDeleteList.add(goodsList.get(i));
                waitDeleteMap.put(goodsList.get(i).get("id"),map.get(goodsList.get(i).get("id")));
                if("".equals(ids)){
                    ids=goodsList.get(i).get("id");
                }else{
                    ids=ids+","+goodsList.get(i).get("id");
                }

            }
        }
        MyLog.e("inest"," ids="+ ids);

        final AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(mcontext);
//        normalDialog.setIcon(R.drawable.icon_dialog);

        normalDialog.setTitle("更新购物车");
        normalDialog.setMessage("确定删除选中商品");
        final String finalIds = ids;
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        deleteCart(finalIds);
                        goodsList.removeAll(waitDeleteList);
                        map.remove(waitDeleteMap);
                        priceControl(map);
                        adapter.notifyDataSetChanged();
                    }
                });
        normalDialog.setNegativeButton("关闭",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {


                    }
                });
        // 显示
        normalDialog.show();

    }

    //确定删除弹出
    private void showNormalDialog(final String ids){
        /* @setIcon 设置对话框图标
         * @setTitle 设置对话框标题
         * @setMessage 设置对话框消息提示
         * setXXX方法返回Dialog对象，因此可以链式设置属性
         */

    }
    //全选或反选
    private void AllTheSelected(){
        Map<String,Integer> map=adapter.getPitchOnMap();
        boolean isCheck=false;
        boolean isUnCheck=false;
        Iterator iter = map.entrySet().iterator();
        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            if(Integer.valueOf(entry.getValue().toString())==1)isCheck=true;
            else isUnCheck=true;
        }
        if(isCheck==true&&isUnCheck==false){//已经全选,做反选
            for(int i=0;i<goodsList.size();i++){
                map.put(goodsList.get(i).get("id"),0);
            }
            cb_check_all.setChecked(false);
        }else if(isCheck==true && isUnCheck==true){//部分选择,做全选
            for(int i=0;i<goodsList.size();i++){
                map.put(goodsList.get(i).get("id"),1);
            }
            cb_check_all.setChecked(true);
        }else if(isCheck==false && isUnCheck==true){//一个没选,做全选
            for(int i=0;i<goodsList.size();i++){
                map.put(goodsList.get(i).get("id"),1);
            }
            cb_check_all.setChecked(true);
        }
//        priceControl(map);
        adapter.setPitchOnMap(map);
        adapter.notifyDataSetChanged();
    }
    //控制价格展示
    private void priceControl(Map<String, Integer> pitchOnMap){
        totalCount = 0;
        totalPrice = 0.00;
        for(int i=0;i<goodsList.size();i++){
            if(pitchOnMap.get(goodsList.get(i).get("id"))==1){
                totalCount=totalCount+Integer.valueOf(goodsList.get(i).get("count"));
                double goodsPrice=Integer.valueOf(goodsList.get(i).get("count"))*Double.valueOf(goodsList.get(i).get("price"));
                totalPrice=totalPrice+goodsPrice;
            }
        }
//        tv_total_price.setText("￥ "+totalPrice);
//        tv_go_to_pay.setText("付款("+totalCount+")");
    }

    //获取购物车
    public void getCart(){
        String address = ConstantsUrl.domain + "order/cart";
        HashMap<String, String> map = new HashMap<>();
        HashMap<String, String> header = new HashMap<>();
        MyLog.e("inest","getCart");
        HttpUtils.get(address, null, new getCartCallback() {


            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(getcartdata response, int id) {
                MyLog.e("inest","getCartonResponse");
                ArrayList<getcartdata.cartgoods> cartgoodsList=response.getCart_goods();
//                int count=0;
//                if(cartgoodsList!=null&&cartgoodsList.size()>0){
//                    for (int i=0;i<cartgoodsList.size();i++){
//                        int qty= Integer.parseInt(cartgoodsList.get(i).getQty());
//                        count=count+qty;
//                    }
//                }
                goodsList=new ArrayList<>();
                for(int i=0;i<cartgoodsList.size();i++){
                    HashMap<String,String> map=new HashMap<>();
                    map.put("id",cartgoodsList.get(i).getId());
                    map.put("goods_id",cartgoodsList.get(i).getGoods_id());
                    map.put("name",cartgoodsList.get(i).getGoods_name());
                    map.put("type",cartgoodsList.get(i).getCost_price());
                    map.put("price",cartgoodsList.get(i).getGoods_price());
                    map.put("count",cartgoodsList.get(i).getQty());
                    map.put("imgsrc",cartgoodsList.get(i).getImg_src());
                    goodsList.add(map);
                }
                adapter=new CartAdapter(mcontext,goodsList,true);
                adapter.setRefreshPriceInterface(mcontext);
                listView.setAdapter(adapter);
                adapter.notifyDataSetChanged();


            }
        });
    }


    @Override
    public void refreshPrice(Map<String, Integer> pitchOnMap) {
        priceControl(pitchOnMap);
    }



    public void deleteCart(String ids){
        String address = ConstantsUrl.domain + "order/del_cart";
        HashMap<String, String> map = new HashMap<>();
        map.put("ids", ids);


        HttpUtils.get(address, null, map, new deletecartCallback() {

            @Override
            public void onError(Call call, Exception e, int id) {

            }

            @Override
            public void onResponse(deletecartdata response, int id) {

            }
        });
    }


}
